package com.faneui.transfer.gateway.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.servlet.ServletContextSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; 
 

@Component
public class SessionFilter extends ServletContextSupport implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(SessionFilter.class);
 

	private static final String[] openUrlArr = new String[] { "login" };

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	private boolean isOpenUrl(String url) {
		for (String openUrl : openUrlArr) {
			if (url.indexOf(openUrl) >= 0) {
				return true;
			}
		}
		return false;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String url = httpRequest.getRequestURL().toString();
		// if (false) {
//		if (false) {// 如果不是openUrl，则需要校验登录状态
//			// 从headr中取ticket
//			String ticket = httpRequest.getHeader("access_token");
//			if (StringUtils.isBlank(ticket)) {
//				Cookie[] cookies = httpRequest.getCookies();
//
//				if (cookies != null) {
//					for (Cookie cookie : cookies) {
//						if (cookie.getName().equals("Security-Token")) {
//							String val = URLDecoder.decode(cookie.getValue(), "utf-8");
//							ticket = JSON.parseObject(val, SecurityToken.class).getTicket();
//							break;
//						}
//					}
//				}
//			}
//			// 从header取SecurityToken 从token取ticket
//			if (StringUtils.isBlank(ticket)) {
//				String headers = httpRequest.getHeader("Security-Token");
//				if (!StringUtils.isBlank(headers)) {
//					ticket = JSON.parseObject(headers, SecurityToken.class).getTicket();
//				}
//			}
//			if (StringUtils.isNotBlank(ticket)) {
//				try {
////					OperatorDTO operatorDTO = loginIntegration.checkSessionIsAvailable(ticket);
////					request.setAttribute("curUser", operatorDTO);
//				} catch (Exception e) {
//					httpResponse.setStatus(401);
//				}
//			} else {
//				// 请求跨域操作 不会带token的，但是method是options类型
//				if (httpRequest.getMethod().equalsIgnoreCase("options")) {
//					logger.info("ip:" + getIpAddr(httpRequest) + "请求跨域验证,url:" + url);
//				} else {
//					System.out.println("无会话信息,url:" + url);
//					httpResponse.setStatus(401);
//				}
//			}
//		}
		addHeaders(httpResponse);
		if (httpResponse.getStatus() == 200) {
			chain.doFilter(httpRequest, httpResponse);
		}
	}

	private void addHeaders(HttpServletResponse httpResponse) {
		httpResponse.setHeader("Access-Control-Allow-Origin", "*");
		httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
		httpResponse.setHeader("Access-Control-Max-Age", "3600");
		httpResponse.setHeader("Access-Control-Allow-Headers",
				"Origin, X-Requested-With, Content-Type, Accept,Security-Token");
		httpResponse.setHeader("Access-Control-Expose-Headers", "Location");
	}

	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

}
